<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\User;

class LoginController extends Controller {
    public function __construct() {
        $this->middleware('patch_wechat');
    }

    private function response_user($u) {
        if($u->is_active()){
            session(['app_uid' => $u->id]);
            request()->app_user = $u;
            $url = request()->input('next');
            $url = $url?$url:'/';
            return redirect($url)->send();
        }else{
            return response()->view('app.user.login', ['err' => '您的账户还未激活，管理员会在申请之后的三个工作日内完成审核，请耐心等待!'])->send();
        }
    }

    private function patch_wechat_user($u) {
        $openid = session('wechat_openid');
        if($openid){
            User::where('openid', $openid)->update(['openid' => '']);
            $u->openid = $openid;
            $u->save();
        }
    }

    private function redirect_if_login() {
        $uid = session('app_uid');
        if($uid) return $this->response_user(User::findOrFail(session('app_uid')));

        $openid = session('wechat_openid');
        if($openid){
            $u = User::where('openid', $openid)->first();
            if($u) return $this->response_user($u);
        }
    }

    public function login() {
        if(request()->isMethod('post')){

            $data = request()->all();

            $u = User::login($data);
            if($u) {
                $this->patch_wechat_user($u);
                return $this->response_user($u);
            }else{
                return view('app.user.login', ['err' => '账号或密码错误!', 'data' => $data]);
            }
        }else{
            $this->redirect_if_login();
            return view('app.user.login');
        }
    }

    public function register() {
        if(request()->isMethod('post')){
            $data = request()->all();
            $r = User::check($data);
            if(!$r){
                $u = User::add($data);
                $this->patch_wechat_user($u);
                return view('app.user.register', ['err' => '感谢您注册天下诗苑诗友会，管理员将会在三个工作日内完成审核，届时方可正常登录访问。']);
            }else{
                return view('app.user.register', ['err' => $r, 'data' => $data]);
            }
        }else{
            $this->redirect_if_login();
            return view('app.user.register');
        }
    }
}
